package com.mrs.service.impl;

import com.mrs.common.ResponseResult;
import com.mrs.common.vo.BlogUserLoginVo;
import com.mrs.common.vo.UserInfoVo;
import com.mrs.entity.LoginUser;
import com.mrs.entity.User;
import com.mrs.service.BlogLoginService;
import com.mrs.service.LoginService;
import com.mrs.utils.BeanCopyUtils;
import com.mrs.utils.JwtUtil;
import com.mrs.utils.RedisCache;
import com.mrs.utils.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Objects;

/**
 * description: BlogLoginServiceImpl
 * date: 2022/8/7 22:06
 * author: MR.孙
 */
@Service
public class SystemLoginServiceImpl implements LoginService {

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private RedisCache redisCache;


    @Override
    public ResponseResult login(User user) {
        UsernamePasswordAuthenticationToken authenticationToken=
                new UsernamePasswordAuthenticationToken(user.getUserName(),user.getPassword());
        //因为AuthenticationManager会通过UserDetailsService去比对用户密码,UserDetailsService比对完后会
        //AuthenticationManager.authenticate会有一个返回值,里面封装了UserDetails等信息
        Authentication authenticate = authenticationManager.authenticate(authenticationToken);

        //判断是否通过
        if(Objects.isNull(authenticate)){
            throw new RuntimeException("用户名或者密码错误");
        }
        //获取userId,生成token
        LoginUser loginUser = (LoginUser)authenticate.getPrincipal();
        String userId = loginUser.getUser().getId().toString();
        String jwt = JwtUtil.createJWT(userId);

        //把用户信息存入到redis中
        redisCache.setCacheObject("login:"+userId,loginUser);


        //把token返回
        HashMap<String, String> token = new HashMap<>();
        token.put("token",jwt);
        return ResponseResult.okResult(token);
    }


    /**
     * @description:  退出登录
     * @return: com.mrs.common.ResponseResult
     * @author: MR.孙
     * @date: 2022/9/11 12:33
    */
    @Override
    public ResponseResult logout() {
        //获取当前登录用户的用户id
        Long userId = SecurityUtils.getUserId();
        //删除redis中的用户信息
        redisCache.deleteObject("login:"+userId);
        return ResponseResult.okResult();
    }

}
